//
//  CoreData.m
//  MoneyIndividual
//
//  Created by Le Anh Tai on 1/6/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "CoreData.h"

@implementation CoreData

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

static CoreData *_shared;

+ (CoreData *)shared
{
    if (_shared == nil)
    {
        _shared = [[CoreData alloc] init];
    }
    
    return _shared;
}

- (id)init
{
    if (self = [super init])
    {
        
    }
    
    return self;
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

#pragma mark - Import data

- (void)importData:(NSString *)fileName
{
    NSError* err = nil;
    NSString* dataPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"];
    NSArray* Banks = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
                                                     options:kNilOptions
                                                       error:&err];
    [Banks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSManagedObjectContext *context = [self managedObjectContext];
        
        //Account
        NSManagedObject *account = [self newEntity:ACCOUNT_ENITY];
        [account setValue:[obj objectForKey:NAME_KEY] forKey:NAME_KEY];
        [account setValue:[obj objectForKey:TYPE_KEY] forKey:TYPE_KEY];
        [account setValue:[obj objectForKey:DESCRIPTION_KEY] forKey:DESCRIPTION_KEY];
        
        //Catalog
        NSArray *catalogs = [obj objectForKey:CATALOG_KEY];
        NSMutableSet *catalogObjects = [[NSMutableSet alloc] init];
        for (NSDictionary *dic in catalogs)
        {
            NSManagedObject *catalog = [self newEntity:CATALOG_ENITY];
            [catalog setValue:[dic objectForKey:NAME_KEY] forKey:NAME_KEY];

            [catalogObjects addObject:catalog];
        }

        [account setValue:catalogObjects forKey:CATALOG_KEY];
        
//        //detail
//        NSManagedObject *failedBankDetails = [self newEntity:@"BankDetail"];
//        [failedBankDetails setValue:[NSDate date] forKey:@"closeDate"];//[NSDate dateWithString:[obj objectForKey:@"closeDate"]];
//        [failedBankDetails setValue:[obj objectForKey:@"zip"] forKey:@"zip"];
//        [failedBankDetails setValue:failedBankInfo forKey:@"info"];
//        [failedBankInfo setValue:failedBankDetails forKey:@"detail"];
        
        NSError *error;
        if (![context save:&error]) {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }
    }];
}

#pragma mark - popular Methods
- (NSManagedObject *)newEntity:(NSString *)entityName
{
    NSManagedObject *object = [NSEntityDescription
                               insertNewObjectForEntityForName:entityName
                               inManagedObjectContext:self.managedObjectContext];
    //set default value
    if ([entityName isEqualToString:TRANSACTION_ENTITY])
    {
        [object setValue:[NSDate date] forKey:CREATED_DATE_KEY];
    }
    
    return object;
}

- (NSArray *)fetchEntity:(NSString *)entityName
{
    return [self fetchEntity:entityName withCondition:nil sortAttribute:nil isAscending:NO];
}

- (NSArray*)fetchEntity:(NSString*)entityName withCondition:(NSString*)condition sortAttribute:(NSString*)attribute isAscending:(BOOL)isAscending
{
    NSManagedObjectContext *moc = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:entityName inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    
    // Set example predicate and sort orderings...
    if (condition)
    {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:condition];
        [request setPredicate:predicate];
    }
    
    if (attribute)
    {
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                            initWithKey:attribute ascending:isAscending];
        [request setSortDescriptors:@[sortDescriptor]];
    }
    
    NSError *error;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    if (array == nil)
    {
        // Deal with error...
    }
    
    return array;
}

- (BOOL)deleteObject:(NSManagedObject *)object
{
    if (object == nil && [object isKindOfClass:[NSManagedObject class]] == NO)
    {
        return NO;
    }
    
    [_managedObjectContext deleteObject:object];
    
    return YES;
}

- (NSArray *)accounts
{
    if (_accounts == nil)
    {
        _accounts = [self fetchEntity:ACCOUNT_ENITY];
    }
    
    return _accounts;
}

- (NSManagedObject*)getAccountByType:(TransactionType)type
{
    for (NSManagedObject *account in self.accounts)
    {
        NSNumber *typeNum = [account valueForKeyEx:TYPE_KEY];
        if (typeNum.integerValue == type)
        {
            return account;
        }
    }
    
    return nil;
}
#pragma mark - Core Data stack

// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
- (NSManagedObjectModel *)managedObjectModel
{
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"database" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"database.sqlite"];
    
    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:
         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}


@end
